<script>

export default {
  name: 'BlogApply',
  data () {
    return {
      formData: {
        blogId: '',
        title: '',
        cover: '',
        categoryId: '',
        content: '',
        hasComment: 1,
        blogStatus: 1,
        tagIds: []
      },
      rules: {
        title: [{ required: true, message: '标题不能为空！' }],
        categoryId: [{ required: true, message: '请选择分类！' }],
        content: [{ required: true, message: '请输入博客内容！' }],
        tagIds: [{ required: true, message: '至少选择一个标签！' }]
      },
      coverSrc: '',
      basePath: '',
      uploadUrl: '',
      headers: {},
      categoryList: [],
      tagList: []
    }
  },
  methods: {
    getCategoryList () {
      this.$axios.get('category/select/2').then(data => {
        this.categoryList = [...data]
      }).catch(e => e)
    },
    getTagList () {
      this.$axios.get('tag/select/2').then(data => {
        this.tagList = [...data]
      })
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
      }
      return isImage && isLt20M
    },
    uploadSuccess (res) {
      if (res.code === 200) {
        this.coverSrc = this.basePath + res.data.filename
        this.formData.cover = res.data.filename
      } else {
        this.$message.error(res.msg)
      }
    },
    uploadEditorImage (file, editor, cursorLocation, resetUpload) {
      if (this.beforeUpload(file)) {
        const form = new FormData()
        form.append('file', file)
        form.append('type', 'blog')
        this.$axios.post('upload', form).then(data => {
          const imageSrc = this.basePath + data.filename
          editor.insertEmbed(cursorLocation, 'image', imageSrc)
          resetUpload()
        }).catch(e => e)
      }
    },
    submit (blogStatus) {
      this.$refs.formDataRef.validate(valid => {
        if (valid) {
          this.formData.blogStatus = blogStatus
          this.$axios.post('blog/update', this.formData).then(() => {
            this.$message.success(`${blogStatus === 1 ? '发表博客' : '保存草稿'}成功！`)
            this.$router.push('/home/vip/blog')
          }).catch(e => e)
        }
      })
    },
    getBlogById () {
      this.formData = { ...this.$options.data().formData }
      const blogId = this.$route.query.blogId
      if (blogId) {
        this.$axios.get(`blog/detail/${blogId}`).then(data => {
          this.formData = { ...data, tagIds: data.blogTagList.map(item => item.tagId) }
          this.coverSrc = this.basePath + data.cover
        }).catch(() => {
          this.$router.replace('/home/vip/blog')
        })
      }
    }
  },
  watch: {
    '$route.query': function () {
      this.getBlogById()
    }
  },
  created () {
    this.getBlogById()
    this.getCategoryList()
    this.getTagList()
    this.basePath = process.env.VUE_APP_BASE_PATH
    this.uploadUrl = this.basePath + 'upload'
    this.headers = { token: this.$cookies.get('token') }
  }
}
</script>

<template>
  <div>
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><a href="javascript:;">博客模块</a></el-breadcrumb-item>
        <el-breadcrumb-item>博客管理</el-breadcrumb-item>
        <el-breadcrumb-item>编辑博客</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card>
      <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入博客标题" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="评论">
              <el-radio-group v-model="formData.hasComment">
                <el-radio border :label="1">启用</el-radio>
                <el-radio border :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="formData.categoryId" clearable filterable placeholder="选择分类">
                <el-option v-for="item in categoryList" :key="item.categoryId" :value="item.categoryId" :label="item.name" :disabled="item.status === 2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tagIds">
              <el-select v-model="formData.tagIds" clearable filterable multiple :multiple-limit="4" placeholder="选择标签">
                <el-option v-for="item in tagList" :key="item.tagId" :value="item.tagId" :label="item.name" :disabled="item.status === 2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="headers"
                :data="{type:'avatar'}"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload">
                <img v-if="coverSrc" :src="coverSrc" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <vue-editor useCustomImageHandler @image-added="uploadEditorImage" v-model="formData.content"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="submit(1)">直接发表</el-button>
              <el-button type="warning" @click="submit(2)">保存草稿</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">

</style>
